package cn.com.pajx.pajx_smart_platform.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import cn.com.pajx.pajx_smart_platform.R;
import cn.com.pajx.pajx_smart_platform.api.Api;
import cn.com.pajx.pajx_smart_platform.bean.EventMessage;
import cn.com.pajx.pajx_smart_platform.broadcast.NetBroadcastReceiver;
import cn.com.pajx.pajx_smart_platform.service.AlarmService;
import cn.com.pajx.pajx_smart_platform.service.ForegroundService;
import cn.com.pajx.pajx_smart_platform.tools.AppConstant;
import cn.com.pajx.pajx_smart_platform.tools.CommonUtil;
import cn.com.pajx.pajx_smart_platform.tools.LogUtil;
import cn.com.pajx.pajx_smart_platform.tools.ToastUtil;
import cn.com.pajx.pajx_smart_platform.ui.view.ExitDialog;
import cn.com.pajx.pajx_smart_platform.ui.view.LollipopFixedWebView;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

@SuppressLint("NonConstantResourceId")
public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, NetBroadcastReceiver.NetStatusMonitor {

    @BindView(R.id.webView)
    LollipopFixedWebView mWebView;
    @BindView(R.id.iv_background)
    ImageView ivBackground;

    private String url;
    private PowerManager.WakeLock mWakeLock;
    //监控网络的广播
    private NetBroadcastReceiver netBroadcastReceiver;

    @Override
    protected void onStart() {
        super.onStart();
        registerBroadcastReceiver();
    }

    @Override
    protected void beforeSetContentView() {
        url = Api.BASE_URL + Api.LOGIN;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        // 开启前台服务防止应用进入后台挂掉
        startService(new Intent(this, ForegroundService.class));
        //保持屏幕长亮
        acquireWakeLock();
        //配置WebView
        initWebView();
        //判断是否是6.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //手机状态权限动态申请
            applyPermission();
        }
        //启动定时任务
        initAlarmService();
    }

    /**
     * 注册网络状态广播
     */
    private void registerBroadcastReceiver() {
        //注册网络的广播
        if (netBroadcastReceiver == null) {
            netBroadcastReceiver = new NetBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(netBroadcastReceiver, filter);
            //设置监听
            netBroadcastReceiver.setStatusMonitor(this);
        }
    }

    /**
     * 初始化WebView
     */
    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    private void initWebView() {
        WebView.setWebContentsDebuggingEnabled(true);
        //启用支持javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        //解决5.0以后https及http的交互使用
        mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        mWebView.getSettings().setSavePassword(true);
        initWebClient();
        //不使用缓存
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        mWebView.getSettings().setBlockNetworkImage(false);//解决图片不显示
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setLoadsImagesAutomatically(true); //支持自动加载图
        mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
        mWebView.loadUrl(url);
        // 通过addJavascriptInterface()将Java对象映射到JS对象(注入时机必须是loadUrl之后)
        mWebView.addJavascriptInterface(new PagesRefresh(), "PagesRefresh");//Android类对象映射到js的back对象
        mWebView.addJavascriptInterface(new ExitApp(), "ExitApp");//Android类对象映射到js的back对象
    }

    /**
     * 初始化定时数据的service
     */
    private void initAlarmService() {
        //开启服务执行定时任务
        Intent intent = new Intent(mContext, AlarmService.class);
        startService(intent);
    }

    private void initWebClient() {
        WebChromeClient wcc = new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        };
        mWebView.setWebChromeClient(wcc);

        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                showProgress();
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                hideProgress();
                ivBackground.setVisibility(View.GONE);
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                hideProgress();
                ivBackground.setVisibility(View.GONE);
                super.onReceivedError(view, request, error);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.e("url=" + url);
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }
        });
    }

    @Override
    public void onNetChange(boolean netStatus) {
        LogUtil.e("netStatus=" + netStatus);
        // 要执行的JavaScript代码及参数
        String javascriptCode = "javascript:networkError('" + netStatus + "')";
        mWebView.evaluateJavascript(javascriptCode, null);
    }

    /**
     * JS注入的方法
     * 刷新页面
     */
    public class PagesRefresh {
        // 被JS调用的方法必须加入@JavascriptInterface注解
        @JavascriptInterface
        public void onRefresh() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ivBackground.setVisibility(View.VISIBLE);
                    mWebView.reload();
                }
            });
        }
    }

    /**
     * JS注入的方法
     * 退出app
     */
    public class ExitApp {
        // 被JS调用的方法必须加入@JavascriptInterface注解
        @JavascriptInterface
        public void onExit() {
            runOnUiThread(MainActivity.this::exitApp);

        }
    }

    @SuppressLint({"WakelockTimeout", "Wakelock"})
    private void acquireWakeLock() {
        if (mWakeLock == null) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                    this.getClass().getCanonicalName());
            mWakeLock.acquire();
        }
    }

    private void releaseWakeLock() {
        if (mWakeLock != null) {
            mWakeLock.release();
            mWakeLock = null;
        }
    }

    /**
     * 判断是否有读取手机状态权限
     */
    private void applyPermission() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            // 没有申请过权限，现在去申请
            EasyPermissions.requestPermissions(
                    new PermissionRequest.Builder(this, 100, perms)
                            .setRationale("获取存储权限,用于数据存储")
                            .setPositiveButtonText("允许")
                            .setNegativeButtonText("拒绝")
                            .build());
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //存储及手机状态权限
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        //授权成功
        ToastUtil.toast("权限申请授权成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //授权被拒绝，弹出提示框
        if (EasyPermissions.somePermissionDenied(this, perms.toArray(new String[0]))) {
            new AppSettingsDialog
                    .Builder(this)
                    .setTitle("权限申请")
                    .setRationale("需要获取存储权限，否则无法存储数据")
                    .setPositiveButton("设置")
                    .setNegativeButton("取消")
                    .build()
                    .show();
        }
    }

    @Override
    protected void onRefresh() {
        super.onRefresh();
        ivBackground.setVisibility(View.VISIBLE);
        mWebView.reload();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mWebView.destroy();
        releaseWakeLock();
        if (netBroadcastReceiver != null) {
            unregisterReceiver(netBroadcastReceiver);
        }
    }

    @Override
    protected void onClickBack() {
        //参数必须加',否则js接受异常
        mWebView.evaluateJavascript("javascript:backtrackPage()", value -> LogUtil.e("onReceiveValue: 此处回调结果" + value));
    }

    /**
     * 退出App
     */
    private void exitApp() {
        ExitDialog exitDialog = new ExitDialog(mContext);
        exitDialog.setViewOnClickListener(new ExitDialog.ViewClickListener() {
            @Override
            public void popupChildView() {
                System.exit(0);
            }
        });
        exitDialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage bean) {
        String message = bean.getMessage();
        if (TextUtils.equals(message, AppConstant.ALARM_TASK)) {
            LogUtil.e("定时任务=" + bean.getData());
            //清除缓存，重新加载
            CommonUtil.clearAppCache(mContext);
//            mWebView.reload();
        }
    }
}
